import React from 'react';
import {
  NativeModules,
  Platform,
  NativeAppEventEmitter,
} from 'react-native';

import JPushModule from 'jpush-react-native';
import BaseModel from './BaseModel';
import ToastUtils from '../common/ToastUtils';
import Constants from '../common/Constants';
import ImageUtil from '../pages/common/ImageUtil';
import Routes from '../common/Routes';
// var Routes = require("../common/Routes");

//58dc634effc3c442e4df8409
export default class PushModel extends BaseModel {
  constructor(props) {
    super(props);

    this._isConnect = false;
    this._needInitAlias = false;
    this._needsetTags = false;

    this._registrationID = -101;
    this._userId = -1;
    this._tags = {};

    this._notificationData = null;
  }

  setup(dataManager) {
    // ToastUtils.show("PushModel setup");
    super.setup(dataManager);
    if(Platform.OS === "ios") {
      this._setupIOS();
    }
    else {
      this._setupAndroid();
    }

    JPushModule.addConnectionChangeListener((result) => {
      if (result) {
        // ToastUtils.show('网络已连接')
      } else {
        // ToastUtils.show('网络已断开')
      }
    });

    // setTimeout(()=>{
    //    this._dealOpenNotification({type:"lover"});
    //  }, 1000);
  }

  addTag(key, value) {
    this._tags[key] = value;
    this.setTags();
  }

  setTags() {
    // ToastUtils.show('setTags isConnect:' + this._isConnect);
    if(this._isConnect === false) {
      this._needsetTags = true;
    }
    else {
      this._needInitAlias = false;
      var array = [];
      for (var key in this._tags) {
        if(this._tags[key] != null && this._tags[key] != undefined) {
          array.push(this._tags[key]);
        }
      }
      if(array.length === 0) {
        array.push("visitor");
      }
      JPushModule.setTags(array, (result)=> {
        // ToastUtils.show('setTags success:' + JSON.stringify(result));
      });
    }
  }

  initAlias() {
    // ToastUtils.show('initAlias:' + this._isConnect);
    if(this._isConnect === true) {
      this._needInitAlias = false;
      let userId = this.dataManager.getModel(Constants.MODULE_TYPE.USER).getSelfData().user_id;
      if(userId != this._userId) {
        this._userId = userId;
        JPushModule.setAlias(userId, (result)=> {
          // ToastUtils.show('setAlias result:' + JSON.stringify(result) + " userId:" + userId + " registrationID:" + this._registrationID);
        });
      }
    }
    else {
      this._needInitAlias = true;
    }
  }

  _setupIOS() {
    JPushModule.addnetworkDidLoginListener(() => {
        // ToastUtils.show('连接已登录');
        this._isConnect = true;
        JPushModule.getRegistrationID((registrationID) => this._registrationID = registrationID);
        if(this._needInitAlias === true) {
          this.initAlias();
        }
        if(this._needsetTags === true) {
          this.setTags();
        }
      });
    NativeAppEventEmitter.addListener('receiveNotification', this._onReceiveNotificationIOS.bind(this));
    NativeAppEventEmitter.addListener('receivePushMsg', this._onReceivePushMsgIOS.bind(this));
    // NativeAppEventEmitter.addListener('openNotification', this._openNotification.bind(this));
    JPushModule.addReceiveOpenNotificationListener(this._receiveOpenNotificationListener.bind(this));
    JPushModule.addOpenNotificationLaunchAppListener(this._openNotificationLaunchAppListener.bind(this));
  }

  // _openNotification(event) {
    // ToastUtils.show("_openNotification" + JSON.stringify(event));
  // }

  _receiveOpenNotificationListener(event) {
    // ToastUtils.show("_receiveOpenNotificationListener" + JSON.stringify(event));
    this._dealOpenNotification(event);
  }

  _openNotificationLaunchAppListener(event) {
    // ToastUtils.show("_openNotificationLaunchAppListener" + JSON.stringify(event));
    this._dealOpenNotification(event);
  }

  _onReceiveNotificationIOS(message) {
    // 下面就是发送过来的内容，可以用stringfy打印发来的消息
    console.log("content: " + JSON.stringify(message));
    // ToastUtils.show("_onReceiveNotificationIOS: " + JSON.stringify(message));
  }

  //自定义消息
  _onReceivePushMsgIOS(message) {
    // ToastUtils.show("_onReceivePushMsgIOS: " + JSON.stringify(message));
  }

  _dealOpenNotification(notification) {
    this._notificationData = notification;
    // ToastUtils.show("_dealOpenNotification: " + JSON.stringify(notification));
    Routes.goNotification(notification);
    //{"aps":{"alert":"222"},"notice_type":"1","_j_uid":11146571352,"love_id":"595f8*****","_j_msgid":4823848032***,"_j_business":1}
  }

  getNotificationData() {
    return this._notificationData;
  }

  clearNotificationData() {
    this._notificationData = null;
  }

  _setupAndroid() {
    // ToastUtils.show("setupAndroid");
    JPushModule.notifyJSDidLoad(() => {
      // ToastUtils.show('连接已登录');
      // console.log("Device register succeed, registrationId " + registrationId);
      this._isConnect = true;
      if(this._needInitAlias === true) {
        this.initAlias();
      }
      if(this._needsetTags === true) {
        this.setTags();
      }
      // JPushModule.getInfo((map) => {
  		// 	this.setState({
  		// 		appkey: map.myAppKey,
  		// 		imei: map.myImei,
  		// 		package: map.myPackageName,
  		// 		deviceId: map.myDeviceId,
  		// 		version: map.myVersion
  		// 	});
  		// });
      JPushModule.getRegistrationID((registrationID) => {
        this._registrationID = registrationID;
      })

      JPushModule.addReceiveOpenNotificationListener(this._receiveOpenNotificationListener.bind(this));
      JPushModule.addOpenNotificationLaunchAppListener(this._openNotificationLaunchAppListener.bind(this));
      JPushModule.addReceiveNotificationListener((notification) => {
        // ToastUtils.show("addReceiveNotificationListener: " + JSON.stringify(notification))
      });
    });
    JPushModule.initPush();
  }
}
